package com.sam.im.heiqun.uis.activities;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputFilter;
import android.text.InputType;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.entities.UpdateProfileEntivity;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.utils.JudgeIDCard;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.data.safe.MD5;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.text.ParseException;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 重新设置密码
 */
public class NewPasswordActivity extends BaseSwipeBackActivity implements Handler.Callback {

    private static final String TAG = NewPasswordActivity.class.getSimpleName();
    public static final int REQUEST_COUNTRY = 1000;
    public static final int TIME_SUB = 1002;

    @BindView(R.id.right)
    ImageView right;
    @BindView(R.id.get_sign)
    TextView getSign;
    @BindView(R.id.auth_code)
    EditText authCode;
    @BindView(R.id.password)
    EditText password;
    @BindView(R.id.again_password)
    EditText againPassword;
    @BindView(R.id.phone_number)
    EditText phoneNumber;
    @BindView(R.id.sure)
    Button sure;
    @BindView(R.id.activity_new_password)
    LinearLayout activityNewPassword;
    @BindView(R.id.pre_v_back)
    ImageView preVBack;

    @BindView(R.id.country)
    TextView country;
    @BindView(R.id.country_code)
    TextView countryCode;

    String type;
    private PGService mPGservice;
    private String authInfo;
    private String countryStr;
    private String mobileCode = "+86";
    private int timeNum = 60;
    private Handler handler = new Handler(this);
    private UserEntivity userEntivity = ToolsUtils.getUser();
    private int tag = -1 ;
    /**
     * 线程通讯   handler
     */
    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case TIME_SUB :
                timeNum-- ;
                if (timeNum > 0) {
                    getSign.setText(timeNum + "s");
                    handler.sendEmptyMessageDelayed(TIME_SUB, 1000);
                } else {
                    getSign.setText(R.string.get_auth_code);
                    getSign.setTextColor(getResources().getColor(R.color.colorAccent));
                    timeNum = 60;
                    getSign.setEnabled(true);
                }
                break;
        }
        return false;
    }
    private static class MyHandler extends Handler {

    }
    /**
     * 界面布局
     */
    @Override
    public int getContentViewId() {
        return R.layout.activity_new_password;
    }

    /**
     * 标题设置
     */
    @Override
    protected String getTitleText() {
        type = getIntent().getStringExtra("type");
        tag = getIntent().getIntExtra("tag",-1);
        if (type != null) {
            return type;
        } else {
            type = getResources().getString(R.string.find_psd);
            return getResources().getString(R.string.find_psd);
        }
    }

    /**
     * 界面逻辑
     */
    @Override
    protected void initViews(Bundle savedInstanceState) {

        countryStr = getResources().getString(R.string.chain);

        if (type != null) {
            if (getResources().getString(R.string.real_name_approve).equals(type)) {
                password.setHint(R.string.name);
                againPassword.setHint(R.string.id_card);
                password.setInputType(InputType.TYPE_CLASS_TEXT);
                againPassword.setInputType(InputType.TYPE_CLASS_TEXT);

                if (userEntivity.getIsAuth() == 1) {
                    authCode.setVisibility(View.GONE);
                    getSign.setVisibility(View.GONE);
                    phoneNumber.setText(userEntivity.getMobile());
                    phoneNumber.setFocusable(false);

                    password.setText(userEntivity.getRealName());
                    password.setFocusable(false);
                    againPassword.setText(userEntivity.getIdNo());
                    againPassword.setFocusable(false);
                    sure.setText(getResources().getString(R.string.shenghe_ing));
                } else if (userEntivity.getIsAuth() == 2) {
                    authCode.setVisibility(View.GONE);
                    getSign.setVisibility(View.GONE);
                    phoneNumber.setText(userEntivity.getMobile());
                    phoneNumber.setFocusable(false);

                    password.setText(userEntivity.getRealName());
                    password.setFocusable(false);
                    againPassword.setText(userEntivity.getIdNo());
                    againPassword.setFocusable(false);
                    sure.setText(getResources().getString(R.string.shenhe_success));

                } else if (userEntivity.getIsAuth() == 3) {
                    authCode.setVisibility(View.GONE);
                    getSign.setVisibility(View.GONE);
                    phoneNumber.setText(userEntivity.getMobile());
                    phoneNumber.setFocusable(false);

                    password.setText(userEntivity.getRealName());
                    password.setFocusable(false);
                    againPassword.setText(userEntivity.getIdNo());
                    againPassword.setFocusable(false);
                    sure.setText(getResources().getString(R.string.shenhe_fail));
                }

            } else if (getResources().getString(R.string.alter_psd).equals(type)) {
                password.setHint(R.string.new_psd);
                againPassword.setHint(R.string.affirm_new_psd);
            } else if (getResources().getString(R.string.set_pay_psd).equals(type)) {
                password.setHint(R.string.please_imput_six_psd);
                againPassword.setHint(R.string.affirm_pay_psd);
                password.setInputType(InputType.TYPE_CLASS_NUMBER);
                againPassword.setInputType(InputType.TYPE_CLASS_NUMBER);
                password.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
                againPassword.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
                password.setTransformationMethod(PasswordTransformationMethod.getInstance());
                againPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
            } else if (getResources().getString(R.string.find_psd).equals(type)) {
                Log.i("info", "找回密码请求");
            }
        } else {
            password.setHint(R.string.psd);
            againPassword.setHint(R.string.affirm_psd);
        }
        mPGservice = PGService.getInstance();
    }

    /**
     * 点击事件处理
     */
    @OnClick({R.id.get_sign, R.id.sure, R.id.pre_v_back, R.id.country})
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.get_sign:
                String phoneNumberStr = phoneNumber.getText().toString().trim();
                boolean isMobileNO = ToolsUtils.isMobileNO(phoneNumberStr);
                if (!isMobileNO) {
                    showToast(getResources().getString(R.string.error_phone));
                    return;
                }
                if (tag==-1){
                    if (!phoneNumberStr.equals(ToolsUtils.getUser().getMobile())){
                        showToast(getString(R.string.pleaseinputthismobile));
                        return;
                    }
                }
                //这里判断是否是缓存中的手机号不科学  移除
               /* UserEntivity userEntivity = ToolsUtils.getUser();
                if (null != userEntivity && !phoneNumberStr.equals(userEntivity.getMobile())) {
                    showToast(getResources().getString(R.string.please_self_phone_number));
                    return;
                }*/
                if (phoneNumberStr.length() > 0 && phoneNumberStr.length() <= 11) {
                    getSign.setEnabled(false);
                    Log.i("info","==="+mobileCode+"==="+phoneNumberStr);
                    getValidateNum(mobileCode + phoneNumberStr);
                }
                break;

            case R.id.sure:
                doCommit();
                break;

            case R.id.pre_v_back:
                scrollToFinishActivity();
                break;

            case R.id.country:
                startActivityForResult(CountrySelectActivity.class, REQUEST_COUNTRY);
                break;
        }
    }

    /**
     * 启动 Activity 返回处理
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_COUNTRY:
                    countryStr = data.getStringExtra("country");
                    country.setText(countryStr);
                    mobileCode = data.getStringExtra("mobileCode");
                    countryCode.setText(mobileCode);
                    break;
            }
        }
    }

    /**
     * 提交按钮 判定
     */
    private void doCommit() {

        String mobile = phoneNumber.getText().toString().trim();
        String pwd = password.getText().toString().trim();
        String againPwd = againPassword.getText().toString().trim();
        String authStr = authCode.getText().toString().trim();

        if (getResources().getString(R.string.real_name_approve).equals(type)) {
            if (userEntivity.getIsAuth() == 0) {
                if (authStr.equals("")) {
                    showToast(getResources().getString(R.string.please_import_auth_code));
                    return;
                }
                updateAuth();
            }
        } else if (getResources().getString(R.string.alter_psd).equals(type) | getResources().getString(R.string.find_psd).equals(type)) {
            if (authStr.equals("")) {
                showToast(getResources().getString(R.string.please_import_auth_code));
                return;
            }
            if (pwd.length() < 6) {
                showToast(getResources().getString(R.string.password_least_six));
                return;
            }
            if (mobile.length() > 11) {
                showToast("手机号长度不能大于11");
                return;
            }

            if (pwd.equals(againPwd)) {
                if (getResources().getString(R.string.alter_psd).equals(type) | getResources().getString(R.string.find_psd).equals(type)) {
                    Log.i("info", "执行找回密码请求");
                    findPwd();
                }
            } else {
                showToast(getResources().getString(R.string.password_unify));
            }
        } else if (getResources().getString(R.string.set_pay_psd).equals(type)) {
            if (pwd.length() != 6) {
                showToast(getResources().getString(R.string.pay_psw_must6));
                return;
            }
            if (null==againPwd||"".equals(againPwd)){
                ToolsUtils.showToast(NewPasswordActivity.this,getResources().getString(R.string.pok_pay_psw));
                return;
            }
            if (!pwd.equals(againPwd)){
                ToolsUtils.showToast(NewPasswordActivity.this,getResources().getString(R.string.psw_two_fail));
                return;
            }
            if (pwd.length() > 15) {
                showToast("密码长度不能大于11");
                return;
            }
            setPayPwd();
        }
    }

    /**
     * 实名认证
     */
    private void updateAuth() {
        if (!ToolsUtils.currentNetState(this)) {
            return;
        }
        showProgress(null);
        final String name = password.getText().toString().trim();
        final String idCard = againPassword.getText().toString().trim();
        final String auth = authCode.getText().toString().trim();
        final String mobile = phoneNumber.getText().toString().trim();

        try {
            String s = JudgeIDCard.IDCardValidate(idCard);
            if (!"".equals(s)) {
                hideProgress();
                showToast(s);
                return;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        String userId = ToolsUtils.getMyUserId();
        mPGservice.updateAuth(name, auth, userId, idCard, mobileCode + mobile).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
                showToast(getString(R.string.real_name_affirm_defeat));
                hideProgress();
            }

            @Override
            public void onNext(ValidateEntivity validateEntivity) {
                hideProgress();
                showToast(getString(R.string.data_already_commit_please_wait_approve));
                UserEntivity user = ToolsUtils.getUser();
                user.setIsAuth(1);
                user.setIdNo(idCard);
                user.setRealName(name);
                user.save();
                finish();
            }
        });

    }

    /**
     * 设置支付密码
     */
    private void setPayPwd() {
        showProgress(null);
        String pwd = password.getText().toString().trim();
        String validateNum = authCode.getText().toString().trim();
        final String payPsd = MD5.MD532(pwd);
        mPGservice.setPayPwd(payPsd, ToolsUtils.getMyUserId(), validateNum).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
                Log.i("info","ex"+ex.getDisplayMessage()+ex.getCode());
                hideProgress();
                try {
                    String displayMessage = ex.getDisplayMessage();
                    JSONObject obj = new JSONObject(displayMessage);
                    JSONObject data = obj.getJSONObject("data");
                    String info = data.getString("info");
                    showToast(info+"");
                }catch (Exception e){
                    ToolsUtils.showToast(NewPasswordActivity.this,getResources().getString(R.string.caozuo_fail));
                }
            }
            @Override
            public void onNext(ValidateEntivity validateEntivity) {
                hideProgress();
                showToast(getResources().getString(R.string.set_success));
                UserEntivity user = ToolsUtils.getUser();
                user.setPayInfo(payPsd);
                user.save();
                finish();
            }
        });
    }

    /**
     * 修改，找回密码
     */
    public void findPwd() {

        if (!ToolsUtils.currentNetState(this)) {
            return;
        }
        final String psdStr = password.getText().toString().trim();
        String authStr = authCode.getText().toString().trim();
        final String mobileStr = phoneNumber.getText().toString().trim();

        //if (authStr.equals(authInfo)) {
            showProgress(null);
            mPGservice.findPwd(mobileCode + mobileStr, psdStr, authStr).subscribe(new AbsAPICallback<UpdateProfileEntivity>() {
                @Override
                protected void onResultError(ApiException ex) {
                    hideProgress();
                    if (type.equals(getResources().getString(R.string.find_psd))){
                        showToast(getResources().getString(R.string.psw_getold_fail));
                    }else {
                        showToast(getResources().getString(R.string.psd_alter_defeat_please_try_again));
                    }
                }

                @Override
                public void onNext(UpdateProfileEntivity validateEntivity) {
                    hideProgress();
                    UserEntivity userEntivity = ToolsUtils.getUser();
                    ToolsUtils.saveUser(userEntivity, userEntivity.getMobilePrefix(), mobileStr, psdStr);
                    if (type.equals(getResources().getString(R.string.find_psd))){
                        showToast(getResources().getString(R.string.psw_getold_success));
                        EventBus.getDefault().post("1");
                    }else {
                        showToast(getString(R.string.alter_success));
                    }
                    finish();
                }
            });
       /* } else {
            showToast(getResources().getString(R.string.auth_code_error));
        }*/
    }

    /**
     * 获取验证码
     */
    private void getValidateNum(String phoneNumber) {
        mPGservice.getValidateNum(phoneNumber).subscribe(new AbsAPICallback<ValidateEntivity>() {

            @Override
            public void onNext(ValidateEntivity s) {//成功之后才开始倒计时
                getSign.setText(timeNum + "s");
                getSign.setTextColor(getResources().getColor(R.color.middle_gray_2));
                handler.sendEmptyMessageDelayed(TIME_SUB, 1000);
                authInfo = s.getInfo();
                authCode.setText(s.getInfo());
            }

            @Override
            protected void onResultError(ApiException ex) {
                getSign.setEnabled(true);
                if (ex.getCode() == 2) {
//                    showToast(getResources().getString(R.string.phoneiserror));
                    try {

                        com.alibaba.fastjson.JSONObject object = JSON.parseObject(ex.getDisplayMessage());
                        com.alibaba.fastjson.JSONObject data = object.getJSONObject("data");

                        showToast(data.getString("info"));
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                } else {
                    showToast(getResources().getString(R.string.net_visit_exception1));
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        /*InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.windowDismissed(this.getWindow().getDecorView().getWindowToken()); // hide method
        imm.startGettingWindowFocus(null);*/
        handler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }
}
